package com.example.nacos.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 服务发现控制器
 */
@RestController
@RequestMapping("/discovery")
public class DiscoveryController {
    
    @Autowired
    private DiscoveryClient discoveryClient;
    
    /**
     * 获取所有服务列表
     */
    @GetMapping("/services")
    public List<String> getServices() {
        return discoveryClient.getServices();
    }
    
    /**
     * 获取指定服务的所有实例
     */
    @GetMapping("/instances/{serviceName}")
    public List<Map<String, Object>> getInstances(@PathVariable String serviceName) {
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceName);
        return instances.stream().map(instance -> {
            Map<String, Object> info = new HashMap<>();
            info.put("serviceId", instance.getServiceId());
            info.put("host", instance.getHost());
            info.put("port", instance.getPort());
            info.put("uri", instance.getUri().toString());
            info.put("metadata", instance.getMetadata());
            return info;
        }).collect(Collectors.toList());
    }
    
    /**
     * 获取本服务信息
     */
    @GetMapping("/local")
    public Map<String, Object> getLocalServiceInfo() {
        Map<String, Object> result = new HashMap<>();
        result.put("description", discoveryClient.description());
        result.put("services", discoveryClient.getServices());
        return result;
    }
}

